<?php
/**
 * Created by PhpStorm.
 * User: Charles
 * Date: 2017/11/1
 * Time: 21:29
 */

namespace app\Http\Controllers\Wechat;


use App\Http\Controllers\Controller;
use App\Models\Domain;
use App\Models\EasyWechat;
use App\Models\MemberAccount;
use App\Models\MemberAccountLog;
use App\Models\MyWechatUpload;
use App\Models\Order;
use App\Models\WechatPay;
use App\Models\WechatUpload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

class PaymentController extends Controller
{
    public function getPay(Request $request)
    {
        $this->validate($request, ['id' => 'required|int']);
        $wechatUpload = WechatUpload::findOrFail($request->id);
        if ($wechatUpload->openid == Session::get('wechat_openid')) {
            return response()->redirectTo('/wechat/view?id=' . $request->id);
        }
        $myWechatUpload = MyWechatUpload::query()
            ->where('wechat_upload_id', $request->id)
            ->where('openid', Session::get('wechat_openid'))
            ->first();
        if (null !== $myWechatUpload) {
            return response()->redirectTo('/wechat/view?id=' . $request->id);
        }
        $price = percentile_rand($wechatUpload->min_price, $wechatUpload->max_price);
        return view('wechat.payment.pay', compact('wechatUpload', 'price'));
    }

    public function getPaying(Request $request)
    {
        $domain = $request->domain;
        $domainModel = Domain::query()
            ->where('domain', $domain)
            ->where('status', 1)
            ->first();
        if (null === $domainModel) {
            $domain = $request->getHttpHost();
        }
        $price = (double) $request->price;
        $wechatUpload = WechatUpload::findOrFail($request->id);
        if ($wechatUpload->openid == Session::get('wechat_openid')) {
            return response()->redirectTo('/wechat/view?id=' . $request->id);
        }
        $myWechatUpload = MyWechatUpload::query()
            ->where('wechat_upload_id', $request->id)
            ->where('openid', Session::get('wechat_openid'))
            ->first();
        if (null !== $myWechatUpload) {
            return response()->redirectTo('/wechat/view?id=' . $request->id);
        }
        if ($price < $wechatUpload->min_price) {
            $price = $wechatUpload->max_price;
        }
        $order = Order::query()
            ->where('wechat_upload_id', $wechatUpload->id)
            ->where('openid', Session::get('wechat_openid'))
            ->where('amount', $price)
            ->where('created_at', '<', Carbon::now()->addDays(300)->toDateTimeString())
            ->first();
        if (null === $order) {
            $order = new Order();
            $order->wechat_upload_id = $wechatUpload->id;
            $order->openid = Session::get('wechat_openid');
            $order->amount = $price;
            $order->status = 1;
            $order->save();
        }
        if (2 == $order->status) {
            return response()->redirectTo('/wechat/view?id=' . $request->id);
        }
        if (3 == $order->status) {
            abort(400, '订单已经退款');
        }
        $wechatPay = new WechatPay($price, Session::get('wechat_openid'), $order);
        $json = $wechatPay->getPaymentJsonString();
        return view('wechat.payment.paying', compact('wechatUpload', 'json', 'order', 'domain'));
    }

    public function anyNotify(Request $request)
    {
        $response = EasyWechat::getApp()->payment
            ->handleNotify(function ($notify, $successful) {
                Log::info($notify);
                if (!$successful) {
                    return true;
                }
                if (empty($notify->out_trade_no)) {
                    return true;
                }
                $order = Order::query()
                    ->where('number', $notify->out_trade_no)
                    ->first();
                if (null === $order) {
                    return true;
                }
                $order->status = 2;
                $order->save();
                $wechatUpload = WechatUpload::find($order->wechat_upload_id);
                if (null === $wechatUpload) {
                    return true;
                }
                // 是否有购买记录
                $myWechatUpload = MyWechatUpload::query()
                    ->where('openid', $order->openid)
                    ->where('wechat_upload_id', $order->wechat_upload_id)
                    ->first();
                if (null === $myWechatUpload) {
                    $myWechatUpload = new MyWechatUpload();
                    $myWechatUpload->openid = $order->openid;
                    $myWechatUpload->type = $wechatUpload->type;
                    $myWechatUpload->wechat_upload_id = $order->wechat_upload_id;
                    $myWechatUpload->save();
                    $wechatUpload->buy_count ++;
                    $wechatUpload->total_price += $order->amount;
                    $wechatUpload->save();
                    $memberAccount = MemberAccount::firstOrNew(['openid' => $wechatUpload->openid]);
                    if (empty($memberAccount->balance)) {
                        $memberAccount->balance = 0;
                    }
                    $memberAccount->balance += $order->amount;
                    $memberAccount->save();
                    if ($order->member) {
                        $order->member->paid += $order->amount;
                        $order->member->save();
                    }
                    $memberAccountLog = new MemberAccountLog();
                    $memberAccountLog->openid = $wechatUpload->openid;
                    $memberAccountLog->type = 2;
                    $memberAccountLog->price = $order->amount;
                    $memberAccountLog->comment = '收到打赏';
                    $memberAccountLog->wechat_upload_id = $order->wechat_upload_id;
                    $memberAccountLog->save();
                }
                return true;
            });
        $response->send();
        exit();
    }
}